// 1. React核心库
import React, { useState, useRef } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Space, Tag, Tooltip, Popconfirm, Modal, Form, Select, DatePicker } from 'antd';

// 3. 图标库
import { 
  PlusOutlined, 
  DeleteOutlined, 
  ReloadOutlined,
  UserOutlined,
  TeamOutlined
} from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 7. 生成的类型定义 (必须使用，禁止手工定义)
import type { UserRole, AssignRoleRequest } from '@/services/generated/src/index';

const { Option } = Select;

const UserRolesPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [assignModalVisible, setAssignModalVisible] = useState(false);
  const [users, setUsers] = useState<any[]>([]);
  const [roles, setRoles] = useState<any[]>([]);
  const [form] = Form.useForm();

  // 加载用户列表
  const loadUsers = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.users.usersList({
        page: 1,
        pageSize: 100,
      });
      const responseData = (response as any).data || response;
      setUsers(responseData?.items || []);
    } catch (error) {
      console.error('加载用户列表失败:', error);
    }
  };

  // 加载角色列表
  const loadRoles = async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesList({
        page: 1,
        pageSize: 100,
        isActive: true,
      });
      const responseData = (response as any).data || response;
      setRoles(responseData?.items || []);
    } catch (error) {
      console.error('加载角色列表失败:', error);
    }
  };

  // 删除用户角色关联
  const handleDelete = async (userRoleId: number) => {
    try {
      await autoLoginInDev();
      await apiClients.permissions.permissionsUserRolesDestroy({ id: userRoleId });
      message.success('用户角色关联删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量分配角色
  const handleBatchAssign = async (values: any) => {
    try {
      await autoLoginInDev();
      
      const request: AssignRoleRequest = {
        user_ids: values.user_ids,
        role_ids: values.role_ids,
        expires_at: values.expires_at?.toISOString(),
      };
      
      await apiClients.permissions.permissionsUserRolesBatchAssignCreate({
        assignRoleRequest: request
      });
      
      message.success('角色分配成功');
      setAssignModalVisible(false);
      form.resetFields();
      actionRef.current?.reload();
    } catch (error) {
      message.error('角色分配失败');
    }
  };

  // 打开分配模态框
  const handleOpenAssignModal = () => {
    loadUsers();
    loadRoles();
    setAssignModalVisible(true);
  };

  // 表格列定义
  const columns: ProColumns<UserRole>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '用户',
      dataIndex: 'user_name',
      width: 150,
      render: (_, record) => (
        <Space>
          <UserOutlined />
          <span>{record.user_name}</span>
        </Space>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      width: 150,
      render: (_, record) => (
        <Space>
          <TeamOutlined />
          <Tag color="blue">{record.role_name}</Tag>
        </Space>
      ),
    },
    {
      title: '分配者',
      dataIndex: 'assigned_by_name',
      width: 120,
      search: false,
    },
    {
      title: '分配时间',
      dataIndex: 'assigned_at',
      width: 180,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '过期时间',
      dataIndex: 'expires_at',
      width: 180,
      search: false,
      valueType: 'dateTime',
      render: (_, record) => {
        if (!record.expires_at) return '-';
        const isExpired = record.is_expired;
        return (
          <Tag color={isExpired ? 'red' : 'green'}>
            {new Date(record.expires_at).toLocaleString()}
          </Tag>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 100,
      valueType: 'select',
      valueEnum: {
        true: { text: '激活', status: 'Success' },
        false: { text: '禁用', status: 'Error' },
      },
      render: (_, record) => {
        let color = 'green';
        let text = '激活';
        
        if (!record.is_active) {
          color = 'red';
          text = '禁用';
        } else if (record.is_expired) {
          color = 'orange';
          text = '已过期';
        }
        
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (_, record) => [
        <Tooltip key="delete" title="删除关联">
          <Popconfirm
            title="确定要删除该用户角色关联吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Tooltip>,
      ],
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户角色管理',
        subTitle: '管理用户和角色的关联关系',
      }}
    >
      <ProTable<UserRole>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          try {
            await autoLoginInDev();

            const response = await apiClients.permissions.permissionsUserRolesList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.user_name || params.role_name,
              isActive: params.is_active,
            });

            console.log('🚀 用户角色列表API响应:', response);

            // 🔑 关键：手动提取data字段
            const responseData = (response as any).data || response;
            return {
              data: responseData?.items || [],
              success: true,
              total: responseData?.total || 0,
            };
          } catch (error) {
            message.error('获取用户角色列表失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        dateFormatter="string"
        headerTitle="用户角色关联列表"
        toolBarRender={() => [
          <Button
            key="refresh"
            icon={<ReloadOutlined />}
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
          <Button
            key="assign"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleOpenAssignModal}
          >
            分配角色
          </Button>,
        ]}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
      />

      {/* 分配角色模态框 */}
      <Modal
        title="批量分配角色"
        open={assignModalVisible}
        onCancel={() => {
          setAssignModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleBatchAssign}
        >
          <Form.Item
            name="user_ids"
            label="选择用户"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择要分配角色的用户"
              showSearch
              filterOption={(input, option) =>
                (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
              }
            >
              {users.map(user => (
                <Option key={user.id} value={user.id}>
                  {user.username} ({user.full_name || user.email})
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="role_ids"
            label="选择角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择要分配的角色"
              showSearch
              filterOption={(input, option) =>
                (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
              }
            >
              {roles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.display_name} ({role.name})
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="expires_at"
            label="过期时间"
            help="不设置则永不过期"
          >
            <DatePicker
              showTime
              placeholder="请选择过期时间（可选）"
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserRolesPage;
